"""
模块概述：登录数据处理
作者：张浩
创建时间：2021-3-4
更新时间：2021-3-15
"""
# 导入数据库模块
import pymysql
# 导入Flask框架，这个框架可以快捷地实现了一个WSGI应用
from flask import Flask, flash
# 默认情况下，flask在程序文件夹中的templates子文件夹中寻找模块
from flask import render_template
# 导入前台请求的request模块
from flask import request, Blueprint, session
import traceback


# 传递根目录
zh_app = Blueprint('zh_app', __name__)


# 获取数据库连接
def get_conn():
    conn = pymysql.connect(
        host='139.217.107.173',
        port=3306,
        user='root',
        password='123456',
        database='project_training',
        charset='utf8'
    )
    cursor = conn.cursor()
    # 返回conn和cursor
    return conn, cursor


# 资源释放
def my_close(conn, cursor):
    conn.close()
    cursor.close()


# 获取登录参数及处理
@zh_app.route('/zh_login_result', methods=['get','post'])
def zh_login():
    conn, cursor = get_conn()
    # SQL 查询语句
    sql = "select * from userinfo where username= %s and password= %s and isadminan= %s"
    user = request.values.get('user')
    password = request.values.get('password')
    isadminan = request.values.get('isadminan')
    content = [user, password, isadminan]
    try:
        print(user, password, isadminan)
        # 执行sql语句
        cursor.execute(sql, content)
        results = cursor.fetchall()

        print(len(results))
        if len(results) == 1:
            uid = results[0][0]
            session['user'] = user
            session['isadminan'] = isadminan
            session['uid'] = uid
            my_close(conn, cursor)
            u = session.get('user')
            flash("你好！"+user)
            if isadminan == '企业':
                return render_template('homepage1.html', u=u)
            else:
                return render_template('homepage2.html', u=u)
        else:
            my_close(conn, cursor)
            # return '用户名或密码不正确'
            flash("用户名或密码错误！")
            session['user'] = 'guest'
            session['isadminan'] = 'guest'
            u = session.get('user')
            return render_template('homepage.html', u=u)

    except:
        # 如果发生错误则回滚
        # my_close(conn, cursor)
        traceback.print_exc()
        conn.rollback()
    # 关闭数据库连接
    my_close(conn, cursor)
